﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Framework;
using TemplateEngine.TranslateCommand;

namespace TemplateEngine.TranslateFunctions
{
    internal class PositionFunction : ICommand
    {
        private static TemplateNode GetEachNode(TemplateNode node)
        {
            if (node.Parent == null || node.Parent.CommandStr == "each")
            {
                return node.Parent;
            }

            return GetEachNode(node.Parent);
        }

        public string Execute(System.Xml.XmlNode xmlNode, TemplateNode templateNode, object[] args)
        {
            // 获取最近的循环节点
            TemplateNode eachNode = GetEachNode(templateNode);
            if (eachNode == null)
            {
                TemplateEngineException ex = new TemplateEngineException("Position函数必须放在Each节点以下");
                TemplateLogger.Error(ex);
                throw ex;
            }

            EachTranslate each = (EachTranslate)eachNode.Translate;
            return each.Index.ToString();
        }
    }
}
